package cn.sym.pet.service.impl;

import cn.sym.basic.exception.MyException;
import cn.sym.basic.service.impl.BaseServiceImpl;
import cn.sym.basic.util.BaiduAuditUtils;
import cn.sym.basic.util.CodeGenerateUtils;
import cn.sym.basic.util.DistanceUtil;
import cn.sym.basic.util.Point;
import cn.sym.org.domain.Shop;
import cn.sym.org.mapper.ShopMapper;
import cn.sym.pet.domain.OrderPetAcquisition;
import cn.sym.pet.domain.Pet;
import cn.sym.pet.domain.SearchMasterMsg;
import cn.sym.pet.domain.SearchMasterMsgAuditLog;
import cn.sym.pet.dto.HandleMsgDto;
import cn.sym.pet.mapper.OrderPetAcquisitionMapper;
import cn.sym.pet.mapper.PetMapper;
import cn.sym.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.sym.pet.mapper.SearchMasterMsgMapper;
import cn.sym.pet.service.ISearchMasterMsgService;
import cn.sym.user.domain.User;
import cn.sym.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sym
 * @since 2022-02-27
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    /**
     * 发布寻主消息
     * @param searchMasterMsg
     */
    @Override
    public void publish(SearchMasterMsg searchMasterMsg, User user) {
        System.out.println("user的结果："+user.getId());
        //查询出当前登录人
        searchMasterMsg.setUserId(user.getId());
        //保存信息
        searchMasterMsgMapper.add(searchMasterMsg);
        //自动审核
        StringBuilder sb = new StringBuilder();
        String auditText = searchMasterMsg.getName()+" "+searchMasterMsg.getTitle()+searchMasterMsg.getAddress();
        if (!BaiduAuditUtils.TextCensor(auditText)){
            sb.append("请输入合法的信息！");
        }
        String note = sb.toString();
        //表示校验成功，没有不合法信息
        if (StringUtils.isEmpty(note)) {
            //发布寻主消息的人的地址
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            //寻找最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            //如果shop存在，就绑定给这个店铺
            if (nearestShop != null) {
                //设置寻主消息的shopId为查询出来的最近店铺的id
                searchMasterMsg.setShopId(nearestShop.getId());
                //并发送信息，短信或者邮件告知此店铺
                //  SmsUtil.sendSms(nearestShop.getTel() ,"亲爱的店主您好，在你的附近有宠物需要领养哟，请记得关注哦！！");
            }
            //如果没有找到放入寻主池-不做任何处理
            //修改状态
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核通过！");
            searchMasterMsgMapper.update(searchMasterMsg);
            //审核通过也要记录日志
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setMsgId(searchMasterMsg.getId());
            auditLog.setState(1);
            auditLog.setAuditTime(new Date());
            auditLog.setNote("审核通过！");
            searchMasterMsgAuditLogMapper.add(auditLog);
        }else {
            //如果审核失败，驳回。用户就可以在前台修改完成继续提交审核、
            searchMasterMsg.setState(-1);
            searchMasterMsg.setNote(note);
            searchMasterMsgMapper.update(searchMasterMsg);
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setMsgId(searchMasterMsg.getId());
            auditLog.setState(-1);
            auditLog.setAuditTime(new Date());
            auditLog.setNote(note);
            searchMasterMsgAuditLogMapper.add(auditLog);
        }
    }

    /**
     *接单
     * @param handleMsgDto
     */
    @Override
    public void accept(HandleMsgDto handleMsgDto) {
        //判断当前寻主消息，是否已经被接单
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgIdAndPending(handleMsgDto.getMsgId());
        if(order != null){
            // 根据寻主消息id查询 查询收购表 且订单状态是：state=0
            throw new MyException("哦豁，该消息已经被别人接单！！！");
        }
        //没有被接单
        SearchMasterMsg masterMsg = searchMasterMsgMapper.loadById(handleMsgDto.getMsgId());
        //生成宠物
        Pet pet = masterMsg2Pet(masterMsg);
        petMapper.add(pet);
        //生成收购单--绑定操作人
        order = initOrderPetAcquisition(handleMsgDto, masterMsg, pet);
        orderPetAcquisitionMapper.add(order);
    }

    private OrderPetAcquisition initOrderPetAcquisition(HandleMsgDto handleMsgDto, SearchMasterMsg masterMsg, Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //设置生成的订单的状态为待确认状态
        order.setState(0);
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(handleMsgDto.getHandlerId()));
        order.setDigest(masterMsg.getName() +":收购单");
        //超时自定取消订单
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));
        order.setPrice(new BigDecimal(masterMsg.getPrice()));
        order.setPetId(pet.getId());
        order.setUserId(masterMsg.getUserId());
        order.setShopId(masterMsg.getShopId());
        order.setAddress(masterMsg.getAddress());
        order.setEmpId(handleMsgDto.getHandlerId());//绑定上门收购宠物的店员
        order.setSearchMasterMsgId(masterMsg.getId());
        return order;
    }

    private Pet masterMsg2Pet(SearchMasterMsg masterMsg) {
        Pet pet = new Pet();
        pet.setName(masterMsg.getName());
        /**
         * saleprice
         * costprice  上门收购宠物之后，确认收购单，来填写价格
         */
        pet.setTypeId(masterMsg.getPetType());
        pet.setShopId(masterMsg.getShopId());
        pet.setSearchMasterMsgId(masterMsg.getId());
        return pet;
    }

    /**
     * 拒单
     * @param msgId
     */
    @Override
    public void reject(Long msgId) {
        //把消息的shopId置空即可
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        //把店铺id置空，就是把宠物放回寻主池
        msg.setShopId(null);
        searchMasterMsgMapper.update(msg);
    }


}
